using Castle.MonoRail.Framework;
using NHibernate;

namespace NhibernateDemoMvc.Filters
{
    public class TransactionFilter : Filter
    {
        private ISession session
        {
            get { return SessionFactoryAccessor.Factory.GetCurrentSession(); }
        }


        protected override bool OnBeforeAction(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            session.BeginTransaction();
            return true;
        }

        protected override void OnAfterAction(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            using (session.Transaction)
            {
                if (context.LastException == null)
                {
                    session.Transaction.Commit();
                }
                else
                {
                    session.Transaction.Rollback();
                }
            }
        }
    }
}